package com.demo;

import static io.r2dbc.pool.PoolingConnectionFactoryProvider.INITIAL_SIZE;
import static io.r2dbc.pool.PoolingConnectionFactoryProvider.MAX_SIZE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import static io.r2dbc.spi.ConnectionFactoryOptions.HOST;
import static io.r2dbc.spi.ConnectionFactoryOptions.PASSWORD;
import static io.r2dbc.spi.ConnectionFactoryOptions.PORT;
import static io.r2dbc.spi.ConnectionFactoryOptions.PROTOCOL;
import static io.r2dbc.spi.ConnectionFactoryOptions.USER;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import reactor.core.publisher.Mono;

public class Demo1 {
	private static Logger logger = LoggerFactory.getLogger(Demo1.class);
	private static String userName = PropertiesInnerUtil.getString(Constant.DATASOURCE_LOCATION, "datasource.username");
	private static String password = PropertiesInnerUtil.getString(Constant.DATASOURCE_LOCATION, "datasource.password");

	public static void main(String[] args) throws InterruptedException {

		ConnectionFactory connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
				   .option(DRIVER, "pool")
				   .option(PROTOCOL, "mysql") // driver identifier, PROTOCOL is delegated as DRIVER by the pool.
				   .option(HOST, "10.16.9.34")
				   .option(PORT, 3306)
				   .option(USER, userName)
				   .option(PASSWORD, password)
				   .option(DATABASE, "sms_crm_db")
				   .option(INITIAL_SIZE, 1)
				   .option(MAX_SIZE, 10)
				   .build());
		Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

		CountDownLatch down = new CountDownLatch(1);
		connectionMono.subscribe(connection -> {
			logger.warn("1: " + connection);
			// 归还连接
			Mono.from(connection.close()).subscribe();
			down.countDown();
		});
		down.await();

		CountDownLatch down2 = new CountDownLatch(1);
		connectionMono.subscribe(connection -> {
			logger.warn("2: " + connection);
			Mono.from(connection.close()).subscribe();
			down2.countDown();
		});
		down2.await();
	}

}
